#include "agv_entity.h"
#include <cmath>

namespace kernel {
namespace agv {

AgvEntity::AgvEntity(int agvId, int agvNumber)
    : m_id(agvId)
    , m_number(agvNumber)
    , m_lastUploadTime(std::chrono::system_clock::now())
    , m_lastBusyTime(std::chrono::system_clock::now())
{
}

bool AgvEntity::needsCharging() const
{
    // 低电量判断逻辑
    if (m_batteryLevel < 40 && !m_isCharging && m_isOnline) {
        return true;
    }

    // 空闲充电判断（电量低于80%且长时间空闲）
    auto now = std::chrono::system_clock::now();
    auto idleSeconds = std::chrono::duration_cast<std::chrono::seconds>(
        now - m_lastBusyTime).count();

    if (idleSeconds > 600 && m_batteryLevel < 80 && !m_isCharging && !m_isControlledByDispatcher) {
        return true;
    }

    return false;
}

bool AgvEntity::canAcceptTask() const
{
    return m_isOnline
        && !m_isBusy
        && !m_isControlledByDispatcher
        && !m_isCharging
        && !m_isLocked
        && !m_currentStation.empty();
}

bool AgvEntity::isAtStation(const std::string& stationName) const
{
    return m_currentStation == stationName;
}

double AgvEntity::getDistanceTo(double x, double y) const
{
    double dx = m_position.x - x;
    double dy = m_position.y - y;
    return std::sqrt(dx * dx + dy * dy);
}

void AgvEntity::updateLastUploadTime()
{
    m_lastUploadTime = std::chrono::system_clock::now();
}

void AgvEntity::updateLastBusyTime()
{
    m_lastBusyTime = std::chrono::system_clock::now();
}

} // namespace agv
} // namespace kernel
